package cn.zyjw.service.impl;

import cn.zyjw.domain.SysMenu;
import cn.zyjw.model.RolePrivilegesParam;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Sets;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zyjw.mapper.SysRolePrivilegeMapper;
import cn.zyjw.domain.SysRolePrivilege;
import cn.zyjw.service.SysRolePrivilegeService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysRolePrivilegeServiceImpl extends ServiceImpl<SysRolePrivilegeMapper, SysRolePrivilege> implements SysRolePrivilegeService {


    /**
     * 配置角色权限保存
     *
     * @param rolePrivilegesParam
     * @return
     */
    @Override
    @Transactional
    public boolean grantPrivileges(RolePrivilegesParam rolePrivilegesParam) {
        @NotNull Long roleId = rolePrivilegesParam.getRoleId();
        @NotNull Set<Long> privilegeIds = rolePrivilegesParam.getPrivilegeIds();
        //删除之前的角色关联
        this.baseMapper.delete(
                Wrappers.<SysRolePrivilege>lambdaQuery()
                        .eq(SysRolePrivilege::getRoleId, roleId)
        );
        if (CollectionUtils.isNotEmpty(privilegeIds)) {
            //插入角色关联数据
            Set<SysRolePrivilege> sysRolePrivileges = Sets.newHashSet();
            for (Long privilegeId : privilegeIds) {
                SysRolePrivilege sysRolePrivilege = new SysRolePrivilege();
                sysRolePrivilege.setPrivilegeId(privilegeId);
                sysRolePrivilege.setRoleId(roleId);
                sysRolePrivileges.add(sysRolePrivilege);
            }
            return this.saveBatch(sysRolePrivileges);
        }
        return true;
    }
}
